'use strict'
const { flaw_type_B } = require('../flaw_type');
const { cf_pol_db_config } = require('../config.json').station_db; // 源库
const { linedb_cf_pol_config } = require('../config.json').line_db; // 源库
const seq = require('../lib/db').getSequelizeInstance(cf_pol_db_config);
const seq1 = require('../lib/db').getSequelizeInstance(linedb_cf_pol_config);

const { initJobData_2, Job_2 } = require('./../model/2/job');
const { initSheetData_2, Sheet_2 } = require('./../model/2/sheet');
const { initPolAoiData_2, PolAoui_2 } = require('./../model/2/pol_aoi');
const { initFlawData_2, Flaw_2 } = require('./../model/2/flaw');
const { initFlawTypeData_2, FlawType_2 } = require('./../model/2/flaw_type');
const { initStationData_2, Station_2 } = require('./../model/2/station');
const { initStation, station } = require('../model/2/station1');
const DATE = require('../date')
class B {

    constructor() {
        initStation(seq1)
        initJobData_2(seq);
        initSheetData_2(seq);
        initPolAoiData_2(seq);
        initFlawData_2(seq);
        initFlawTypeData_2(seq);
        initStationData_2(seq);
        this.flawUid = 0;
        this.flawArry = [];
        this.ok_number = 0;
        this.ng_number = 0;
        this.cuurntJobUid = 0;
        this.jobUid = 0;
        this.doffSum = 0;
        this.currentDoff = 0;
        this.time = DATE;
        this.init();
    }

    async init() {
        await this.getAsyncMaxPanelUid();
        this.createFlawTpeStation();
        // this.createStatonData();
        this.createJobInfo();
    }
    async getAsyncMaxPanelUid() {
        try {
            let job_uid = await Job_2.getMaxUid(seq);
            this.jobUid = job_uid;
            let flaw_uid = await Flaw_2.getMaxUid(seq);
            this.flawUid = flaw_uid;
        } catch (_) {
            console.log(_);
        }
    }

    createStatonData() {
        const stationData = flaw_type_B.map((item, index) => {
            return {
                id: index + 1,
                flaw_class_type: item.id,
                station_id: item.camera_id,
                station_name: item.station
            }
        })
        this.uploadInfo(station, stationData, 'station——目标')
    }
    createFlawTpeStation() {
        let flawType = [];
        let station = [];
        flaw_type_B.forEach((item, index) => {
            flawType.push({
                id: index + 1,
                flaw_class_type: item.id,
                show: item.show,
                color: item.color,
                shape: item.shape,
                symbol: item.symbol
            })
            // station.push({
            //     id: index + 1,
            //     station_id: item.camera_id,
            //     station_name: item.station
            // })
        })
        this.uploadInfo(FlawType_2, flawType, 'CF_POL-flaw_type');
        // this.uploadInfo(Station_2, station, 'CF_POL-station');
    }
    async createPanelInfo(panelInfo, time) {
        this.time = time;
        if (panelInfo.flawCount) {
            panelInfo.flawCount = Math.floor(Math.random() * 20);
        }
        this.createJob(this.job, panelInfo);
        await this.createPanel(panelInfo);
        this.createFlaw(panelInfo, this.job);
        // this.createFlawTpeStation();
    }
    /**
     * 
     * @param {时间戳} date 
     * @returns 格式化后的时间
     */
    formatDate(date) {
        let time = new Date(date);
        let minites = time.getMinutes() < 10 ? `0${time.getMinutes()}` : time.getMinutes();
        let seconds = time.getSeconds() < 10 ? `0${time.getSeconds()}` : time.getSeconds();
        return `${time.toLocaleDateString()} ${time.getHours()}:${minites}:${seconds}`;
    }
    createJobInfo() {
        this.doffSum = Math.floor(Math.random() * 20) + 10;
        let JobInfo = {
            uid: ++this.jobUid,
            jobName: `CF_POL工单${this.jobUid}`,
            orderNumber: `CF_POL批次${Math.floor(this.jobUid / 5) + 1}`,
            doffSum: this.doffSum,
            createTime: this.time,
            finishTime: this.time + 888,
            exConfig1: '{"job": {"modelSize": { "value": "8192;32000" } }}',
            lot_number: `LOTID0000${Math.floor(this.jobUid / 2) + 1}`
        }
        this.job = JobInfo;
    }
    createFlaw(panelInfo, job) {
        let flawResultArr = this.createFlawInfo(panelInfo, job);
        if (!flawResultArr) return false;
        let flawInfoArr = flawResultArr.map(item => {
            return {
                uid: item.uid,
                job_id: item.jobId,
                sheet_id: item.doffId,
                camera_id: item.cameraId,
                class_id: item.flawClassType,
                center_pos_md: item.dMD,
                center_pos_cd: item.dCD,
                length_md: item.dLength,
                length_cd: item.dWidth,
                gen_time: this.time,
                gen_time_str: this.formatDate(this.time),
                save_path: item.content,
                ui_show_text: item.symbol
            }
        })
        // console.log(station);
        this.uploadInfo(Flaw_2, flawInfoArr, 'CF_POL-flaw');
    }
    // 创建各个缺陷
    createFlawInfo(panelInfo, job) {
        if (!panelInfo.flawCount) return;
        let flawArry = [];
        for (let i = 0; i < panelInfo.flawCount; i++) {
            const dWidth = Math.random() * 2;
            const dLength = Math.random() * 2;
            const flawTypeIndex = Math.floor(Math.random() * (flaw_type_B.length - 1));
            flawArry.push({
                uid: ++this.flawUid,
                jobId: this.job.uid,
                doffId: panelInfo.uid,
                flawClassType: flaw_type_B[flawTypeIndex].id,
                dShape: flaw_type_B[flawTypeIndex].shape,
                cameraId: flaw_type_B[flawTypeIndex].camera_id,
                station: flaw_type_B[flawTypeIndex].station,
                show: flaw_type_B[flawTypeIndex].show,
                symbol: flaw_type_B[flawTypeIndex].symbol,
                color: flaw_type_B[flawTypeIndex].color,
                dCD: Math.random() * panelInfo.length_cd,
                dMD: Math.random() * panelInfo.length_md,
                dWidth,
                dLength,
                dArea: dWidth * dLength,
                dDiameter: Math.random() * 2,
                createTime: this.time,
                content: "http://192.168.1.200:5555/rts.png",
                detectParam: panelInfo.detectParam,
            })
        }
        return flawArry;
    }
    async createPanel(panelInfo) {
        ++this.currentDoff
        if (this.currentDoff == this.doffSum) {
            this.createJobInfo();
            this.currentDoff = 0;
        }
        const sheet = {
            uid: panelInfo.uid,
            job_id: this.job.uid,
            flaw_count: panelInfo.flawCount,
            head_md: panelInfo.head_md,
            length_md: panelInfo.length_md,
            length_cd: panelInfo.length_cd,
            gen_time: panelInfo.startTime,
            gen_time_str: this.formatDate(panelInfo.startTime),
        }
        const polAoi = {
            id: panelInfo.uid,
            panel_id: panelInfo.panelId,
            sheet_id: panelInfo.uid
        }
        await this.uploadInfo(Sheet_2, sheet, 'CF_POL-sheet');
        await this.uploadInfo(PolAoui_2, polAoi, 'CF_POL-pol_aoi');
    }
    createJob(job, panelIfo) {
        if (this.cuurntJobUid != this.job.uid) {
            this.ok_number = 0;
            this.ng_number = 0;
            this.cuurntJobUid = this.job.uid;
        }
        if (panelIfo.flawCount == 0) {
            this.ok_number++;
        } else {
            this.ng_number++;
        }
        const jobInfo = {
            uid: this.job.uid,
            job_name: job.jobName,
            lot_number: job.lot_number,
            sheet_sum: job.doffSum,
            start_time: job.createTime,
            start_time_str: this.formatDate(job.createTime),
            finish_time: job.finishTime,
            finish_time_str: this.formatDate(job.finishTime),
            ok_number: this.ok_number,
            ng_number: this.ng_number
        }
        this.uploadInfo(Job_2, jobInfo, 'CF_POL-Job');
    }
    // 上传
    async uploadInfo(operater, jobInfo, tableName) {
        try {
            let res = await operater.upload(jobInfo);
            if (res.length || res.dataValues) {
                console.log(`${tableName} sucess`);
            }
        } catch (error) {
            console.log(error);
        }
    }
    static getInstance() {
        return new B();
    }
}

module.exports = B.getInstance();